package com.example.leetdemo.plan1;

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;

public class Sword037 {

    public int[] asteroidCollision(int[] asteroids) {
        Deque<Integer> stack = new ArrayDeque<>();
        stack.push(asteroids[0]);
        for (int i = 1; i < asteroids.length; i++) {
            while (stack.size() != 0 && asteroids[i] < 0 && stack.peekLast() > 0) {
                if (Math.abs(asteroids[i]) - Math.abs(stack.peekLast()) > 0) {
                    stack.pollLast();
                } else {
                    break;
                }
            }
            if (stack.size() > 0 && asteroids[i] < 0 && stack.peekLast() > 0) {
                if (Math.abs(asteroids[i]) - Math.abs(stack.peekLast()) == 0) {
                    stack.pollLast();
                }
            } else {
                stack.addLast(asteroids[i]);
            }
        }
        int[] re = new int[stack.size()];
        int i = 0;
        while (stack.size() > 0) {
            re[i] = stack.pollFirst();
            i++;
        }
        return re;
    }

    public static void main(String[] args) {
        Sword037 sword037 = new Sword037();
        System.err.println(Arrays.toString(sword037.asteroidCollision(new int[]{-2,1,-1,-2})));
        System.err.println(Arrays.toString(sword037.asteroidCollision(new int[]{2,10,-5})));
    }
}
